<template>
    <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="30%"
    @close="handleClose"
    >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
    >
        <el-form-item label="上级菜单" prop="parent_id">
            <el-select v-model="form.parent_id" placeholder="请选择上级菜单">
                <template v-for="item in tableData">
                    <el-option :label="item.name" :value="item.id"></el-option>
                    <template v-for="child in item.children">
                        <el-option :label="child.name" :value="child.id">
                            <span>{{ " -- " + child.name }}</span>
                        </el-option>
                    </template>
                </template>
            </el-select>
        </el-form-item>
        <el-form-item label="菜单类型" prop="menu_type" label-width="100px">
            <el-radio-group v-model="form.menu_type">
                <el-radio :value="'M'">目录</el-radio>
                <el-radio :value="'C'">页面</el-radio>
                <el-radio :value="'F'">按钮</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.menu_type !== 'F'" label="菜单图标" prop="icon">
            <el-input v-model="form.icon" />
        </el-form-item>
        <el-form-item :label="form.menu_type === 'F' ? '按钮名称' : '菜单名称'" prop="name">
            <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item v-if="form.menu_type === 'F'" label="权限标识" prop="perms">
            <el-input v-model="form.perms" placeholder="如: sys:user:add" />
            <div class="api-path-tips mt-1">
                <el-text type="info" size="small">权限字符串，用于前端按钮权限控制</el-text>
            </div>
        </el-form-item>
        <el-form-item v-if="form.menu_type == 'C'" label="API路径" prop="api_path">
            <el-select
                v-model="apiPathList"
                multiple
                filterable
                default-first-option
                placeholder="请选择或输入API路径"
                @change="handleApiPathChange"
                style="width: 100%"
            >
                <el-option
                    v-for="item in routeUrls"
                    :key="item"
                    :label="item"
                    :value="item"
                />
            </el-select>
            <div class="api-path-tips mt-1">
                <el-text type="info" size="small">可以选择多个API路径，用于权限控制</el-text>
            </div>
        </el-form-item>
        <el-form-item v-if="form.menu_type == 'C'" label="组件路径" prop="path">
            <el-input v-model="form.path" />
            <div class="api-path-tips mt-1">
                <el-text type="info" size="small">输入前端视图路径，用于前端路由展示</el-text>
            </div>
        </el-form-item>
        <el-form-item label="显示顺序" prop="order_num" >
            <el-input-number v-model="form.order_num" :min="1" label="显示顺序"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" />
        </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
            <el-button type="primary" @click="handleConfirm">确认</el-button>
            <el-button @click="handleClose">取消</el-button>
        </span>
    </template>
</el-dialog>
</template>

<script setup>
import {defineEmits, defineProps, ref, watch, onMounted} from "vue";
import requestUtil,{getServerUrl} from "@/util/request";
import { ElMessage } from 'element-plus'

const tableData = ref([])

const props=defineProps(
{
    id:{
        type:Number,
        default:-1,
        required:true
    },
    dialogTitle:{
        type:String,
        default:'',
        required:true
    },
    dialogVisible:{
        type:Boolean,
        default:false,
        required:true
    },
    tableData:{
        type:Array,
        default:[],
        required:true
    }
}
)
const form=ref({
    id:-1,
    parent_id:"0",
    menu_type:"M",
    icon:'',
    name:'',
    perms:'',
    api_path:'',
    component:'',
    order_num:1,
    remark:''
})
const rules=ref({
    // 移除上级菜单的必选验证，不选择则自动设置为0
    name: [{ required: true, message: "菜单名称不能为空", trigger: "blur" }],
    api_path: [{ required: true, message: "API路径不能为空", trigger: "blur" }],
    perms: [{ required: true, message: "权限标识不能为空", trigger: "blur" }],
    icon: [{ required: true, message: "菜单图标不能为空", trigger: "blur" }],
    path: [{ required: true, message: "组件路径不能为空", trigger: "blur" }]
})
const formRef=ref(null)
const initFormData=async(id)=>{
    try {
        const res = await requestUtil.get("system/menu/" + id + '/');
        form.value = res;
    } catch (err) {
        console.error("获取菜单信息失败", err)
        ElMessage.error('获取菜单信息失败:' + err)
    }
}

watch(
    ()=>props.dialogVisible,
    ()=>{
        let id=props.id;
        tableData.value=props.tableData;
        if(id!=-1){
            initFormData(id)
        }else{
            form.value={
            id:-1,
            parent_id:'',
            menu_type:"M",
            icon:'',
            name:'',
            perms:'',
            api_path:'',
            component:'',
            order_num:1,
            remark:''
            }
        }
    }
)
const emits=defineEmits(['update:modelValue','initMenuList'])
const handleClose=()=>{
    emits('update:modelValue',false)
}

const apiPathList = ref([])
const routeUrls = ref([])

// 初始化时获取可用的API路径
onMounted(async () => {
    try {
        const res = await requestUtil.get('/system/menu/show_urls/')
        if (res && res.urls) {
            routeUrls.value = res.urls
        }
    } catch (error) {
        ElMessage.error('获取API路径失败:', error)
        console.error('获取API路径失败:', error)
    }
})

// 处理API路径变化
const handleApiPathChange = (val) => {
    // 将数组转换为逗号分隔的字符串
    form.value.api_path = val.join(',')
}

// 监听form.api_path变化，同步到apiPathList
watch(() => form.value.api_path, (newVal) => {
    if (newVal) {
        // 如果是字符串，按逗号分割
        if (typeof newVal === 'string') {
            apiPathList.value = newVal.split(',').map(item => item.trim()).filter(item => item)
        } else if (Array.isArray(newVal)) {
            apiPathList.value = newVal
        } else {
            apiPathList.value = []
        }
    } else {
        apiPathList.value = []
    }
}, { immediate: true })

const handleConfirm=()=>{
  formRef.value.validate(async (valid) => {
    let result;
    if (valid) {
      try {
        // 确保 parent_id 不为空，如果为空则设置为"0"
        if (!form.value.parent_id && form.value.parent_id !== 0) {
          form.value.parent_id = "0";
        }
        
        if (form.value.id === -1) {
          // 新增
          result = await requestUtil.post("system/menu/", form.value);
        } else {
          // 更新
          result = await requestUtil.patch("system/menu/" + form.value.id + "/", form.value); 
        }
        let data = result.data;
        ElMessage.success(form.value.id === -1 ? '添加成功' : '更新成功');
        formRef.value.resetFields();
        emits("initMenuList")
        handleClose();
      } catch (error) {
        ElMessage.error("执行失败！"+error)
      }
    } else {
      ElMessage.error("表单验证失败")
    }
  })
}
</script>